﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Netfraction.Managers
{
    public delegate void PeerEventHandler(RemoteMachine.PeerEventArgs e);

    [System.Runtime.InteropServices.ComVisible(false)]
    public class PeerManager : System.Collections.ObjectModel.KeyedCollection<string, RemoteMachine.Peer>
    {
        public static event PeerEventHandler OnPeerConnectionHandshakeComplete;

        public static void PeerConnectionHandshakeComplete(RemoteMachine.Peer peer)
        {
            if (OnPeerConnectionHandshakeComplete != null)
                OnPeerConnectionHandshakeComplete(new RemoteMachine.PeerEventArgs(peer));
        }

        public PeerManager()
            : base()
        {
        }

        #region Singleton Pattern
        // Use singleton pattern.
        private static PeerManager _instance;

        /// <summary>
        /// Obtain singleton instance of Client
        /// </summary>
        /// <returns></returns>
        public static PeerManager GetInstance()
        {
            // Check instance
            if (PeerManager._instance == null)
            {
                // Initialize instance
                PeerManager._instance = new PeerManager();
            }

            // Return instance
            return PeerManager._instance;
        }
        #endregion Singleton Pattern

        protected override string GetKeyForItem(Netfraction.RemoteMachine.Peer item)
        {
            return item.Identity.ClientId;
        }

        protected override void InsertItem(int index, Netfraction.RemoteMachine.Peer item)
        {
            base.InsertItem(index, item);
            ClientInterface.Peers.PeerOnline(item.Identity, item.IsLocalClient);
        }

        protected override void SetItem(int index, Netfraction.RemoteMachine.Peer item)
        {
            base.SetItem(index, item);
        }

        public void SetItem(string key, Netfraction.RemoteMachine.Peer item)
        {
            int index = base.Items.IndexOf(base[key]);
            if (index >= 0)
            {
                SetItem(index, item);
                ClientInterface.Peers.PeerChanged(item.Identity, item.IsLocalClient);
            }
            else
                return; // raise invalid key exception
        }

        protected override void ClearItems()
        {
            base.ClearItems();
        }
        
        protected override void RemoveItem(int index)
        {
            ClientInterface.Peers.PeerOffline(base.Items[index].Identity, base.Items[index].IsLocalClient);
            
            base.RemoveItem(index);
        }
    }
}
